package com.atguigu.gulimall.product.exception;

import com.atguigu.common.exception.BizCodeEnum;
import com.atguigu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;


// @ControllerAdvice(basePackages ="com.atguigu.gulimall.product.controller")
@Slf4j
@RestControllerAdvice(basePackages ="com.atguigu.gulimall.product.controller")
public class HandlerValidException {

    @ExceptionHandler(value =MethodArgumentNotValidException.class )
    public R handleException(MethodArgumentNotValidException e){
        Map<String,String> map =new HashMap<>();
        e.getFieldErrors().forEach((item)->{
            map.put(item.getField(),item.getDefaultMessage());
        });
        //log.error("错误是"+e);
        return R.error(BizCodeEnum.VALID_EXCEPTION.getCode(),BizCodeEnum.VALID_EXCEPTION.getMsg()).put("data",map);
    }
    //最大的异常
    @ExceptionHandler(value =Throwable.class )
    public R handleException(Throwable throwable){
        log.error("异常是"+throwable);
        return R.error(BizCodeEnum.UNKNOW_EXCEPTION.getCode(),BizCodeEnum.UNKNOW_EXCEPTION.getMsg());
    }
}
